package com.app.shortvideo.base

import android.content.Context
import android.os.Bundle
import android.os.IBinder
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewbinding.ViewBinding
import com.app.shortvideo.net.base.ResponseCode
import com.app.shortvideo.MApplication
import com.app.shortvideo.Session
import com.app.library.base.ApiException
import com.app.library.base.LibActivity
import com.app.library.base.LibViewModel
import com.app.library.utils.ToasterUtils
import com.app.shortvideo.R
import com.blankj.utilcode.util.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus


abstract class BaseActivity<VB : ViewBinding, VM : LibViewModel> : LibActivity<VB, VM>() {

    private var refreshTime = 0L
    var isRefresh = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MApplication.mInstance.getActivityManager()?.onActivityCreated(this, savedInstanceState)
        if (isNeedBus()) {
            EventBus.getDefault().register(this)
        }
       hasNet(true)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isNeedBus())
            EventBus.getDefault().unregister(this)
    }

    override fun beforeSetContentView() {
        super.beforeSetContentView()
        setStatusBar()
    }

    open fun setStatusBar() {
        BarUtils.transparentStatusBar(this)
        BarUtils.setStatusBarLightMode(this, false)
    }
    open fun showKeyBord(editText: EditText) {
        //不阻塞主线程
        CoroutineScope(Dispatchers.IO).launch {
            delay(500L)
            ThreadUtils.runOnUiThread {
                editText.isFocusable = true
                editText.isFocusableInTouchMode = true
                editText.requestFocus()
                editText.setSelection(editText.text.length)//将光标移至文字末尾
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
            }
        }
    }
    fun hasNet(showToast:Boolean? = false): Boolean {
        val netState = NetworkUtils.getNetworkType() != NetworkUtils.NetworkType.NETWORK_NO
        if (showToast==true&&!netState){
            ToasterUtils.showShort(getString(R.string.error_connection_toast_title))
        }
        return netState
    }
    override fun handleApiExp(exception: ApiException) {
        when (exception.code) {
            ResponseCode.INVALID_TOKEN -> {
                Session.clearSession()
            }
            ResponseCode.CODE_10000 -> {
                showToast(exception.msg ?: "")
            }
            ResponseCode.CODE_INVALID_AUTO -> {
            }
            else -> showToast(exception.msg ?: ResponseCode.getStringByCode(this, exception.code))
        }
    }


    open fun isNeedBus(): Boolean {
        return false
    }

    /**
     * 获取点击事件
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view: View? = currentFocus
            if (isHideInput(view, ev)) {
                hideSoftInput(view?.windowToken)
                view?.clearFocus()
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 判定是否需要隐藏
     */
    private fun isHideInput(v: View?, ev: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom: Int = top + v.getHeight()
            val right: Int = left + v.getWidth()
            return !(ev.x > left && ev.x < right && ev.y > top && ev.y < bottom)
        }
        return false
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val manager: InputMethodManager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /**
     * 初始化刷新控件
     */
    fun initRefreshView(
        refreshView: SwipeRefreshLayout,
        offsetDP: Float? = null,
        isRefresh: Boolean? = null,
        refresh: (() -> Unit)? = null
    ) {
        refreshView.setOnRefreshListener {
            refresh?.invoke()
        }
        offsetDP?.let {
            refreshView.setProgressViewOffset(true, 0, SizeUtils.dp2px(it))
        }
        isRefresh?.let {
            refreshView.isRefreshing = it
        }
        mViewModel.refresh.observe(this) {
            refreshView(refreshView, it)
        }
    }

    private fun refreshView(refreshView: SwipeRefreshLayout, isRefresh: Boolean) {
        if (isRefresh) {
            refreshTime = System.currentTimeMillis()
            refreshView.isRefreshing = true
        } else {
            val duration = System.currentTimeMillis() - refreshTime
            if (duration < 600) {
                refreshView.postDelayed({
                    refreshView.isRefreshing = false
                }, 600 - duration)
            } else {
                refreshView.isRefreshing = false
            }
        }
    }
}